import { storeToRefs } from 'pinia'
import shopCartStore from '@/piniastore/shopcart'
import { BookInfo } from '@/piniastore/book/state'
import { ShopCart } from '@/piniastore/shopcart/state'
import Books from '.'
import { ElMessageBox } from 'element-plus'
import { computed, ref, Ref } from 'vue'
import { procDecimalZero } from '@/utils/numberUtil'
import router from '@/router'

type BallType = {
  showorhidden: boolean, // 小球显示还是隐藏
  addBtnTarget: EventTarget | null, // 添加购物车按钮对象
}

// 购物车相关业务 (存放到图书业务中方便管理)
export default class ShopCartClass {
  static store = shopCartStore()
  static storeRefs = storeToRefs(this.store)
  static ball: Ref<BallType> = ref({ showorhidden: false, addBtnTarget: null })
  static isSelectAll = ref(false) // 控制购物车全选还是非全选

  // 购物车列表单个图书选择事件
  static checkEveryCheckbox = () => {
    const isSelectAll = this.store.getShopCartList.every(shopcart => {
      return shopcart.checked
    })
    this.store.storeShopCartList(this.store.getShopCartList)
    this.isSelectAll.value = isSelectAll
  }

  // 购物车列表全选或非全选
  static selectAll = () => {
    // this.store.getShopCartList 如果浏览器没有刷新是从 pinia 的 state 中获取数据否则是从 Local Storage 中取
    const shopCartList = this.store.getShopCartList.map(shopcart => {
      shopcart.checked = this.isSelectAll.value
      return shopcart
    })
    // 如果是从 Local Storage 中购物车数据必须赋值给 pinia 中的 state 从而同步 Local Starage
    this.store.storeShopCartList(shopCartList)
  }

  // 小球初始化状态(将购物上的小球移动到点击添加书籍按钮上)
  static beforeDrop = (ele: Element) => {
    const curBallEle_ = ele as HTMLBodyElement
    // 获取追加图书按钮对象
    const addBtnEle = <HTMLBodyElement>this.ball.value.addBtnTarget!
    // 计算底部小球移动到按钮对象位置的坐标
    const addBtnEleRect = addBtnEle.getBoundingClientRect() // 获取点击按钮位置信息
    const x = addBtnEleRect.left - 35 // 小球X轴(水平)方向需要移动位置
    const y = -(window.innerHeight - addBtnEleRect.top - 45) // 小球Y轴(垂直)方向需要移动位置
    // 将小球父元素移动到Y轴(垂直)位置，由于小球是子元素，所以小球Y轴方向也发生了改变
    curBallEle_.style.transform = `translate3d(0, ${y}px, 0)`
    const inner = curBallEle_.getElementsByClassName('inner')[0] as HTMLBodyElement // 获取小球元素
    inner.style.transform = `translate3d(${x}px, 0, 0)` // 修改小球X轴(水平)方向位置
  }

  // 小球动画 (执行小球飞入购物车中)
  static dropping(ele: Element, done: (...args: any[]) => any) {
    document.body.scrollHeight // 触发重绘
    const curBallEle_ = ele as HTMLBodyElement  // 获取小球父亲元素
    const inner = curBallEle_.getElementsByClassName('inner')[0] as HTMLBodyElement // 获取小球元素
    curBallEle_.style.transform = `translateY(0)` // 父元素Y轴为0
    inner.style.transform = `translateX(0)` // 子元素X轴(水平方向)为0
    done() // 动画结束执行下一个生命周期函数
  }

  // 小球动画结束
  static afterDrop = (ele: Element) => {
    this.ball.value.showorhidden = false // 小球隐藏
    this.ball.value.addBtnTarget = null // 取消保存点击按钮元素
  }

  // 根据用户id获取购物车相关信息
  static findCurUserShopCartLst = async () => {
    await this.store.findCurUserShopCartLst(1) // 根据用户id查询出相关购物车表并将相关列表保存到 pinia 的 state 中 (和 Local Storage 中)
  }

  // 跳转到购物车列表页面
  static toShopCartList = () => {
    router.push({ path: '/shopcartlist' })
  }

  // 添加书籍到后端购物车表中
  static async addBookToShopCart(bookitem: BookInfo) {
    const shopcart: ShopCart = {
      userid: 1, // 用户id
      checked: false,
      bookisbn: bookitem.ISBN, // 书号
      bookname: bookitem.bookname, // 书名
      bookpicname: bookitem.bookpicname, // 书籍对应的图片名
      bookprice: procDecimalZero(bookitem.originalprice * bookitem.discount), // 图书原价 * 折扣
      purcharsenum: 1, // 购买数量
    }
    await ShopCartClass.store.addBookToShopCart(shopcart)
    Books.updateBookNum(1, bookitem.ISBN)
  }

  // 获取正在修改图书对应的购物车id
  static getExistsShopCartID = (bookinfo: BookInfo) => {
    const shopCartList = this.store.shopCartList // 获取 pinia 中的购物车列表
    let shopCart: ShopCart, shopCartId: number = 0
    for (let i = 0; i < shopCartList.length; i++) {
      shopCart = shopCartList[i]
      if (bookinfo.ISBN === shopCart.bookisbn) {
        shopCartId = shopCart.shopcartid!
        break
      }
    }
    return shopCartId
  }

  // 删除当前购买的图书
  static delCurBookFrmSC = async (bookitem: BookInfo) => {
    ElMessageBox.confirm('确定从购物车中删除这本书吗？', '删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    }).then(async () => {
      const curShopCartId = ShopCartClass.getExistsShopCartID(bookitem) // 获取当前图书对应的购物车id
      await this.store.delBookFrmSC(curShopCartId) // 删除购物车中数据
      Books.updateBookNum(0, bookitem.ISBN) // 更新图书列表中对应的图书购买数量
    }).catch(() => {

    })

  }

  // 点击添加图书到购物车时调用小球动画
  static drop = (event: Event) => {
    this.ball.value.showorhidden = true // 显示小球
    this.ball.value.addBtnTarget = event.currentTarget! // 将点击添加购物车的按钮DOM保存起来
  }

  // 购物车列表增加或减少购买图书
  static appOrSubtrBookInShopCart = async (shopcart: ShopCart, event: Event) => {
    const curTarget = <HTMLBodyElement>event.currentTarget
    const className = curTarget.className
    if (className === 'shopcart-operate-add') {
      // 增加购买图书数量
      shopcart.purcharsenum++
    } else if (className === 'shopcart-operate-minus') {
      // 减少购买图书数量
       shopcart.purcharsenum--
    }
    await this.store.appOrSubtrBookFrmShopCart(shopcart)
  }

  // 购物车列表中删除购买的图书
  static delCurBookInSC = (shopcart: ShopCart) => {
    ElMessageBox.confirm('确定从购物车中删除这本书吗？', '删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    }).then(async () => {
      await this.store.delBookFrmSC(shopcart.shopcartid!) // 删除购物车中数据
    }).catch(() => {

    })
  }

  // 修改购物车中购买图书数量
  static appOrSubtrBookFrmShopCart = async (bookitem: BookInfo, event: Event) => {
    const curShopCartId = this.getExistsShopCartID(bookitem)
    const curTarget = <HTMLBodyElement>event.currentTarget
    let purcharsenum: number = 0
    if (curTarget.className === 'shopcart-operate-add') {
      purcharsenum = bookitem.purcharsenum + 1
      this.drop(event)
    } else if (curTarget.className === 'shopcart-operate-minus') {
      purcharsenum = bookitem.purcharsenum - 1
    }
    const shopcart: ShopCart = { // 生成新的购物车中图书数据
      userid: 1,
      shopcartid: curShopCartId,
      checked: false,
      bookisbn: bookitem.ISBN,
      bookname: bookitem.bookname,
      bookpicname: bookitem.bookpicname,
      bookprice: procDecimalZero(bookitem.originalprice * bookitem.discount), // 图书原价 * 折扣
      purcharsenum
    }
    await ShopCartClass.store.appOrSubtrBookFrmShopCart(shopcart) // 更新购物车中对应图书并将结果缓存到 pinia 的 state 中
    Books.updateBookNum(purcharsenum, bookitem.ISBN) // 更新 pinia 中的 state 数据
  }

  // 获取购买图书总数量 + 总价格
  static refreshShopCartList() {
    // 获取购物车总数量
    const totalCount = computed(() => {
      let total = 0
      const shopcartList = ShopCartClass.store.getShopCartList // 获取购物车列表
      if (shopcartList && shopcartList.length > 0) {
        shopcartList.forEach(shopcart => {
          total += shopcart.purcharsenum
        })
      }
      return total
    })
    // 获取购物车总价格
    const totalPrice = computed(() => {
      let price = 0
      const shopcartlist = ShopCartClass.store.getShopCartList
      if (shopcartlist && shopcartlist.length > 0) {
        shopcartlist.forEach(shopcart => {
          price += shopcart.purcharsenum * shopcart.bookprice // 当前图书数量*价格
        })
      }
      return procDecimalZero(price)
    })

    return { totalCount, totalPrice } // {购物车图书数量，购物车总价格}
  }

  // 根据用户id从后端购物车表中获取对应图书购买数量
  static uptBookNumWithSCLstNum = (books: BookInfo[]) => {
    const shopCartList = this.store.getShopCartList // 获取对应用户购物车列表
    shopCartList.forEach(shopcart => {
      books.forEach(book => {
        if (book.ISBN === shopcart.bookisbn) {
          book.purcharsenum = shopcart.purcharsenum
        }
      })
    })
  }

  // 回退上一步
  static back() {
    router.back()
  }

}




